package com.innovation.ic.b1b.monitor.base.handler;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.monitor.base.mapper.CanalAvailableJobLogMapper;
import com.innovation.ic.b1b.monitor.base.mapper.CanalAvailableJobMapper;
import com.innovation.ic.b1b.monitor.base.mapper.CanalMapper;
import com.innovation.ic.b1b.monitor.base.model.Canal;
import com.innovation.ic.b1b.monitor.base.model.CanalAvailableJob;
import com.innovation.ic.b1b.monitor.base.model.CanalAvailableJobLog;
import com.innovation.ic.b1b.monitor.base.pojo.constant.JobDataMapConstant;
import com.innovation.ic.b1b.monitor.base.pojo.enums.ActiveEnum;
import com.innovation.ic.b1b.monitor.base.value.TimeSetConfig;
import lombok.SneakyThrows;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.sql.Date;
import java.util.Random;

/**
 * @desc   canal可用任务处理类
 * @author linuo
 * @time   2023年5月12日10:19:43
 */
public class CanalAvailableJobHandler extends QuartzJobBean {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private HandlerHelper handlerHelper;

    @Resource
    private TimeSetConfig timeSetConfig;

    @Resource
    private CanalAvailableJobMapper canalAvailableJobMapper;

    @Resource
    private CanalAvailableJobLogMapper canalAvailableJobLogMapper;

    @Resource
    private CanalMapper canalMapper;

    @SneakyThrows
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        log.info("开始执行canal可用任务处理");

        // 获取1-5间的随机数
        int min = 1;
        int max = 5;
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        int sleepTime = s * 1000;
        log.info("休眠[{}]秒", s);
        Thread.sleep(sleepTime);

        JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
        int id = jobDataMap.getInt(JobDataMapConstant.ID);
        CanalAvailableJob canalAvailableJob = canalAvailableJobMapper.selectById(id);
        if(canalAvailableJob != null) {
            Canal canal = canalMapper.selectById(canalAvailableJob.getCanalId());
            if (canal != null) {
                String canalName = canal.getName();

                // 存活状态
                Integer active = ActiveEnum.NO.getCode();

                CanalAvailableJobLog canalAvailableJobLog = new CanalAvailableJobLog();
                canalAvailableJobLog.setCanalAvailableJobId(id);
                canalAvailableJobLog.setStartTime(new Date(System.currentTimeMillis()));

                if(Strings.isNullOrEmpty(canal.getIp()) || Strings.isNullOrEmpty(canal.getPort())){
                    String message = canalName + "配置信息不完整,无法检测是否存活";
                    log.info(message);
                    canalAvailableJobLog.setDescription(message);
                }else{
                    // 判断canal是否可用
                    String message = judgeCanalIfActive(canal);
                    if(message == null){
                        active = ActiveEnum.YES.getCode();
                    }else{
                        canalAvailableJobLog.setDescription(message);
                    }
                }

                canalAvailableJobLog.setActive(active);
                int insert = canalAvailableJobLogMapper.insert(canalAvailableJobLog);
                if(insert > 0){
                    log.info("mongodb可用任务日志插入成功");

                    if(active.intValue() == ActiveEnum.NO.getCode().intValue()){
                        // 发送邮件
                        String message = canalName + "出现异常，原因：" + canalAvailableJobLog.getDescription() + "，请查看canal状态并及时进行异常处理。";
                        handlerHelper.sendEmail(canalAvailableJob.getAlarmEmail(), message, null);
                    }
                }
            }else{
                log.info("未在canal表中查询到id=[{}]的配置信息,无法执行监控canal可用任务", canalAvailableJob.getCanalId());
            }
        }else{
            log.info("监控canal可用任务id为[{}]的数据不存在,无法执行任务", id);
        }
    }

    /**
     * 判断canal是否可用
     * @param canal canal配置信息
     * @return 返回判断结果
     */
    private String judgeCanalIfActive(Canal canal) throws InterruptedException {
        String message = null;

        String ip = canal.getIp();
        int port = Integer.parseInt(canal.getPort());
        String destination = "example";

        CanalConnector canalConnector = null;

        try {
            log.info("第一次执行监控canal是否可用任务");
            // 获取canal服务的连接
            canalConnector = CanalConnectors.newSingleConnector(new InetSocketAddress(ip, port), destination, "", "");
            canalConnector.connect();
        }catch (Exception e){
            if(canalConnector != null){
                canalConnector.disconnect();
            }

            log.warn("连接canal出现问题,原因:[{}],待{}秒后重试", e.toString(), timeSetConfig.getRetryWaitTime());
            Thread.sleep(timeSetConfig.getRetryWaitTime() * 1000);

            try {
                log.info("第二次执行监控canal是否可用任务");
                // 获取canal服务的连接
                canalConnector = CanalConnectors.newSingleConnector(new InetSocketAddress(ip, port), destination, "", "");
                canalConnector.connect();
            }catch (Exception e1) {
                if(canalConnector != null){
                    canalConnector.disconnect();
                }

                log.warn("连接canal出现问题,原因:[{}],待{}秒后重试", e1.toString(), timeSetConfig.getRetryWaitTime());
                Thread.sleep(timeSetConfig.getRetryWaitTime() * 1000);

                try {
                    log.info("第三次执行监控canal是否可用任务");
                    // 获取canal服务的连接
                    canalConnector = CanalConnectors.newSingleConnector(new InetSocketAddress(ip, port), destination, "", "");
                    canalConnector.connect();
                }catch (Exception e2) {
                    if(canalConnector != null){
                        canalConnector.disconnect();
                    }

                    log.warn("连接canal出现问题,原因:[{}],canal连接失败", e2.toString());
                    message = e2.toString();
                }
            }
        }finally {
            if(canalConnector != null){
                canalConnector.disconnect();
            }
        }

        if(!Strings.isNullOrEmpty(message)){
            if(message.length() > 100){
                message = message.substring(0, 100);
            }
        }

        return message;
    }
}